package com.iw.point.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.Marchandise;
import com.iw.adoms.entity.QrGoodsCode;
import com.iw.adoms.entity.neum.DepartType;
import com.iw.adoms.entity.neum.Status;
import com.iw.core.utils.EncryptUtils;
import com.iw.core.utils.HibernateUtils;
import com.iw.point.entity.PointMember;
import com.iw.point.entity.PointRecord;
import com.iw.point.entity.PointType;
import com.iw.sms.entity.Sms;

public class SmsPointServer {

    private Session session;

    public SmsPointServer(Session session) {
        this.session = session;
    }

    public HashMap<String, String> doPoints(Sms sms) {

        Transaction t = session.beginTransaction();

        HashMap<String, String> msgMap = null;

        // 1.门店销售后才可以积分
        // String hql = "from QrGoodsCode where iCode = ? and state = ?";
        // QrGoodsCode qr = (QrGoodsCode) HibernateUtils.createQuery(session, hql, sms.getContent().trim(), Status.QR_ABLE_INTEGRAL.getValue()).uniqueResult();
        //
        String iCode = sms.getContent().trim().replaceAll(" ", "");

        // 2.省代出库后就可以积分（2013.04.21）
        //String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
        //		+ "(select dt.id from DepartmentType dt where dt.name=?)) and g.state = ? and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";
//        List<QrGoodsCode> qrList = HibernateUtils.createQuery(session, hql, DepartType.SD.v(), Status.HAS_OUT.getValue(), iCode, Status.QR_HAD_INTEGRAL.getValue()).list();

        //2.到省代了就可以积分（2013.08.06 - 2013-10-10）
        String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
                + "(select dt.id from DepartmentType dt where dt.name != ?))  and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";

        @SuppressWarnings("unchecked")
        List<QrGoodsCode> qrList = HibernateUtils.createQuery(session, hql, DepartType.ZD.v(), iCode, Status.QR_HAD_INTEGRAL.getValue()).list();

        if (qrList != null && !qrList.isEmpty()) {
            QrGoodsCode qr = qrList.get(0);
            hql = "from Goods where qrCode.id = ?";
            @SuppressWarnings("unchecked")
            List<Goods> goodsList = HibernateUtils.createQuery(session, hql, qr.getId()).list();
            if (goodsList != null && goodsList.size() > 0) {
                msgMap = new HashMap<String, String>();

                Marchandise m = goodsList.get(0).getMarchandise();
                Double point = m.getPoint();
                String mobile = sms.getMobile().trim();

                hql = "from PointMember where mobile = ?";
                boolean isNewMember = false;
                PointMember member = (PointMember) HibernateUtils.createQuery(session, hql, mobile).uniqueResult();
                if (member == null) {
                    member = new PointMember();
                    member.setUserName(mobile);
                    member.setMobile(mobile);
                    member.setPassword(EncryptUtils.md5(mobile));
                    member.setInsertTime(new Date());
                    session.save(member);
                    isNewMember = true;
                }
                Double balance = point + member.getBalance();
                member.setBalance(balance); // 给会员加积分
                session.update(member);
                // 记录积分记录
                PointRecord record = new PointRecord();
                record.setBalance(balance);
                record.setPoint(point);
                record.setMember(member);
                record.setType(PointType.POINT);
                record.setInsertTime(new Date());
                record.setiCode(iCode);
                record.setOper("SYMTEM");
                session.save(record);
                qr.setState(Status.QR_HAD_INTEGRAL.getValue());
                session.update(qr);
                if (isNewMember) {
                    // 新顾客：尊敬的客户，您已成功积分100（50）分，兑换规则可登录www.alvinbaby.com查询。客服热线4000-800-866【艾唯】。（68字）
                    msgMap.put("尊敬的客户，", "您已成功积分" + point + "分，兑换规则可登录www.alvinbaby.com查询。客服热线4000-800-866【艾唯】。");
                } else {
                    // 老顾客：尊敬的顾客XXX（系统调出名字），您已成功积分100（50）分，目前积分余额为XXXX分。客服热线4000-800-866【艾唯】（65字）。
                    msgMap.put("尊敬的顾客，" + member.getUserName(), "您已成功积分" + point + "分，目前积分余额为" + balance + "分。客服热线4000-800-866【艾唯】。");
                }
            }

        }
        if (msgMap == null) {
            msgMap = new HashMap<String, String>();
            // 尊敬的客户，您的输入有误，请核实后重新发送。如有疑问可拨打艾唯咨询热线4000-800-866
            msgMap.put("尊敬的客户，", "您的输入有误，请核实后重新发送。如有疑问可拨打艾唯咨询热线4000-800-866【艾唯】。");
        }
        t.commit();

        return msgMap;
    }
}
